<template>
  <div class="app-container" v-loading="loading" element-loading-text="加载中...">
    <div class="detail-container">
      <!-- 基本信息 -->
      <div class="info-section">
        <h3>基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>资产编号：</label>
              <span>{{ assetInfo.assetNo }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>设备号：</label>
              <span>{{ assetInfo.deviceNo }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>设备名称：</label>
              <span>{{ assetInfo.assetName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>位置：</label>
              <span>{{ assetInfo.location }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>规格型号：</label>
              <span>{{ assetInfo.modelNo }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>设备类型：</label>
              <span>{{ getEquipmentTypeName(assetInfo.equipmentTypeCode) }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>制造商：</label>
              <span>{{ assetInfo.manufacturer }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>供应商：</label>
              <span>{{ assetInfo.supplierName }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>使用部门：</label>
              <span>{{ getDeptName(assetInfo.deptId) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>操作人员：</label>
              <span>{{ assetInfo.operatorName }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>购入日期：</label>
              <span>{{ formatDateTime(assetInfo.purchaseDate) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>投产日期：</label>
              <span>{{ formatDateTime(assetInfo.commissioningDate) }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>状态：</label>
              <el-tag :type="getStatusTagType(assetInfo.statusCode)">
                {{ getStatusName(assetInfo.statusCode) }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 模具图片 -->
      <div class="info-section" style="margin-top: 30px;">
        <ImageUpload
          ref="imageUpload"
          v-model="imageList"
          title="模具图片"
          :readonly="true"
        />
      </div>

      <!-- 维修履历 -->
      <div class="info-section" style="margin-top: 30px;">
        <h3>维修履历</h3>
        
        <!-- 查询条件 -->
        <div class="search-form">
          <el-form :model="repairQueryParams" :inline="true" size="small">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="repairQueryParams.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                @change="handleRepairQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleRepairQuery">搜索</el-button>
              <el-button @click="resetRepairQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 维修记录列表 -->
        <el-table :data="repairList" v-loading="repairLoading" border>
          <el-table-column label="创建时间" align="center" prop="createdAt" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="维修单号" align="center" prop="workNo" width="140" />
          <el-table-column label="报修人" align="center" prop="reporterName" width="100" />
          <el-table-column label="紧急程度" align="center" prop="urgencyName" width="100">
            <template slot-scope="scope">
              <el-tag :type="getUrgencyTagType(scope.row.urgency)" size="mini">
                {{ scope.row.urgencyName || '未知' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="步骤名称" align="center" prop="stepName" width="120" />
          <el-table-column label="操作描述" align="center" prop="description" min-width="200" show-overflow-tooltip />
          <el-table-column label="维修人员" align="center" prop="assigneeName" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.assigneeName || '未分配' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="开始时间" align="center" prop="startTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="center" prop="endTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="维修时间" align="center" width="100">
            <template slot-scope="scope">
              <span>{{ calculateRepairTime(scope.row.startTime, scope.row.endTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结果" align="center" prop="result" width="100">
            <template slot-scope="scope">
              <el-tag :type="getResultTagType(scope.row.result)" size="mini">
                {{ getResultName(scope.row.result) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="repairTotal > 0"
          :total="repairTotal"
          :page.sync="repairQueryParams.pageNum"
          :limit.sync="repairQueryParams.pageSize"
          @pagination="getRepairList"
        />
      </div>

      <div style="text-align: right; margin-top: 30px;">
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getAsset } from "@/api/asset/asset";
import { listDept } from "@/api/system/dept";
import { listUser } from "@/api/system/user";
import { getDicts } from "@/api/dict/data";
import { getAssetRepairHistory } from "@/api/asset/asset";
import ImageUpload from "@/views/components/ImageUpload.vue";

export default {
  name: "AssetDetail",
  components: {
    ImageUpload
  },
  data() {
    return {
      // 资产信息
      assetInfo: {},
      // 图片列表
      imageList: [],
      // 部门选项
      deptOptions: [],
      // 用户选项
      userOptions: [],
      // 设备类型选项
      equipmentTypeOptions: [],
      // 状态选项
      statusOptions: [],
      // 报修类型选项
      reportTypeOptions: [],
      // 紧急程度选项
      urgencyOptions: [],
      // 故障类型选项
      faultTypeOptions: [],
      // 维修记录查询参数
      repairQueryParams: {
        pageNum: 1,
        pageSize: 10,
        assetNo: null,
        dateRange: null
      },
      // 维修记录列表
      repairList: [],
      // 维修记录总数
      repairTotal: 0,
      // 加载状态
      loading: true,
      // 维修记录加载状态
      repairLoading: false
    };
  },
  async created() {
    const assetNo = this.$route.params.assetNo;
    this.loading = true;
    try {
      // 先加载字典，避免映射后跳
      await Promise.all([
        this.getDeptOptions(),
        this.getUserOptions(),
        this.getEquipmentTypeOptions(),
        this.getStatusOptions(),
        this.getReportTypeOptions(),
        this.getUrgencyOptions(),
        this.getFaultTypeOptions()
      ]);
      if (assetNo) {
        await this.getAsset(assetNo);
        this.repairQueryParams.assetNo = assetNo;
      }
      await this.getRepairList();
    } catch (error) {
      console.error('加载资产详情失败:', error);
      this.$message.error('加载数据失败，请重试');
    } finally {
      this.loading = false;
    }
  },
  methods: {
    /** 获取资产详情 */
    getAsset(assetNo) {
      return getAsset(assetNo).then(response => {
        this.assetInfo = response.data;
        // 处理图片数据
        const urls = Array.isArray(response.data.imageUrls)
          ? response.data.imageUrls
          : (response.data.imageUrls ? (()=>{ try { return JSON.parse(response.data.imageUrls) } catch(e){ return [] } })() : [])
        
        // 使用 ImageUpload 组件的 initFromUrls 方法处理图片
        this.$nextTick(() => {
          const imageUploadRef = this.$refs.imageUpload;
          if (imageUploadRef) {
            imageUploadRef.initFromUrls(urls);
          }
        });
      });
    },
    /** 获取部门选项 */
    getDeptOptions() {
      listDept().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 获取用户选项 */
    getUserOptions() {
      listUser().then(response => {
        this.userOptions = response.rows;
      });
    },
    /** 获取设备类型选项 */
    getEquipmentTypeOptions() {
      getDicts("equipment_type").then(response => {
        this.equipmentTypeOptions = response.data;
      });
    },
    /** 获取状态选项 */
    getStatusOptions() {
      getDicts("asset_status").then(response => {
        this.statusOptions = response.data;
      });
    },
    /** 获取报修类型选项 */
    getReportTypeOptions() {
      getDicts("report_type").then(response => {
        this.reportTypeOptions = response.data;
      });
    },
    /** 获取紧急程度选项 */
    getUrgencyOptions() {
      getDicts("urgency_level").then(response => {
        this.urgencyOptions = response.data;
      });
    },
    /** 获取故障类型选项 */
    getFaultTypeOptions() {
      getDicts("fault_type").then(response => {
        this.faultTypeOptions = response.data;
      });
    },
    /** 获取维修记录列表 */
    getRepairList() {
      this.repairLoading = true;
      const assetNo = this.assetInfo.assetNo || this.$route.params.assetNo;
      const params = { 
        assetNo: assetNo,
        pageNum: this.repairQueryParams.pageNum,
        pageSize: this.repairQueryParams.pageSize
      };
      if (this.repairQueryParams.dateRange && this.repairQueryParams.dateRange.length === 2) {
        params.startDate = this.repairQueryParams.dateRange[0];
        params.endDate = this.repairQueryParams.dateRange[1];
      }
      
      getAssetRepairHistory(params).then(response => {
        this.repairList = response.rows || [];
        this.repairTotal = response.total || 0;
        this.repairLoading = false;
      }).catch(() => {
        this.repairList = [];
        this.repairTotal = 0;
        this.repairLoading = false;
      });
    },
    /** 维修记录查询 */
    handleRepairQuery() {
      this.repairQueryParams.pageNum = 1;
      this.getRepairList();
    },
    /** 重置维修记录查询 */
    resetRepairQuery() {
      this.repairQueryParams.dateRange = null;
      this.handleRepairQuery();
    },
    /** 图片预览 */
    previewImage(imageUrl) {
      // 使用Element UI的图片预览组件
      this.$alert(`<img src="${imageUrl}" style="width: 100%; max-width: 600px;" />`, '图片预览', {
        dangerouslyUseHTMLString: true,
        customClass: 'image-preview-dialog'
      });
    },
    /** 返回 */
    goBack() {
      this.$router.go(-1);
    },
    /** 获取设备类型名称 */
    getEquipmentTypeName(code) {
      if (!code) return '';
      const type = this.equipmentTypeOptions.find(t => t.dictValue === code);
      return type ? type.dictLabel : code;
    },
    /** 获取部门名称 */
    getDeptName(deptId) {
      if (!deptId) return '';
      const dept = this.deptOptions.find(d => d.deptId === deptId);
      return dept ? dept.deptName : deptId;
    },
    /** 获取操作人员名称 */
    getOperatorName(operatorId) {
      if (!operatorId) return '';
      const user = this.userOptions.find(u => u.userId === operatorId);
      return user ? user.nickName : operatorId;
    },
    /** 获取状态名称 */
    getStatusName(code) {
      if (!code) return '';
      const status = this.statusOptions.find(s => s.dictValue === code);
      return status ? status.dictLabel : code;
    },
    /** 获取状态标签类型 */
    getStatusTagType(code) {
      const typeMap = {
        'ASSET_STATUS_001': 'success',
        'ASSET_STATUS_002': 'danger',
        'ASSET_STATUS_003': 'warning',
        'ASSET_STATUS_004': 'info',
        'ASSET_STATUS_005': 'danger'
      }
      return typeMap[code] || 'info'
    },
    /** 获取报修类型名称 */
    getReportTypeName(code) {
      if (!code) return '';
      const type = this.reportTypeOptions.find(t => t.dictValue === code);
      return type ? type.dictLabel : code;
    },
    /** 获取紧急程度名称 */
    getUrgencyName(code) {
      if (!code) return '';
      const urgency = this.urgencyOptions.find(u => u.dictValue === code);
      return urgency ? urgency.dictLabel : code;
    },
    /** 获取紧急程度标签类型 */
    getUrgencyTagType(code) {
      const typeMap = {
        'URGENT_001': 'danger',
        'URGENT_002': 'warning',
        'URGENT_003': 'primary',
        'URGENT_004': 'success',
        'URGENT_005': 'info'
      }
      return typeMap[code] || 'info'
    },
    /** 获取故障类型名称 */
    getFaultTypeName(code) {
      if (!code) return '';
      const type = this.faultTypeOptions.find(t => t.dictValue === code);
      return type ? type.dictLabel : code;
    },
    /** 计算维修时间 */
    calculateRepairTime(startTime, endTime) {
      if (!startTime || !endTime) return '-';
      const start = new Date(startTime);
      const end = new Date(endTime);
      const diff = end - start;
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      return `${hours}小时${minutes}分钟`;
    },
    /** 获取结果名称 */
    getResultName(result) {
      const resultMap = {
        'SUCCESS': '成功',
        'FAILED': '失败',
        'PARTIAL': '部分成功'
      };
      return resultMap[result] || result || '';
    },
    /** 获取结果标签类型 */
    getResultTagType(result) {
      const typeMap = {
        'SUCCESS': 'success',
        'FAILED': 'danger',
        'PARTIAL': 'warning'
      };
      return typeMap[result] || 'info';
    },
    /** 格式化日期时间显示完整格式 */
    formatDateTime(date) {
      if (!date) return '';

      let dateObj = null;

      // 处理不同类型的输入
      if (typeof date === 'string') {
        // 如果已经是完整的日期时间格式，直接返回
        if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(date)) {
          return date;
        }
        // 如果只有日期部分，添加默认时间
        if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
          return date + ' 00:00:00';
        }
        // 如果包含T（ISO格式），转换为标准格式
        if (date.includes('T')) {
          const cleanDate = date.replace('T', ' ').replace(/\.\d{3}Z?$/, '');
          return cleanDate;
        }
        // 尝试解析其他格式的字符串
        dateObj = new Date(date);
      } else if (date instanceof Date) {
        dateObj = date;
      } else if (typeof date === 'number') {
        dateObj = new Date(date);
      }

      // 如果成功创建了Date对象，格式化为标准格式
      if (dateObj && !isNaN(dateObj.getTime())) {
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        const hours = String(dateObj.getHours()).padStart(2, '0');
        const minutes = String(dateObj.getMinutes()).padStart(2, '0');
        const seconds = String(dateObj.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }

      // 最后尝试使用parseTime函数格式化
      try {
        return this.parseTime(date, '{y}-{m}-{d} {h}:{i}:{s}');
      } catch (e) {
        return '';
      }
    }
  }
};
</script>

<style scoped>
.detail-container {
  background: #fff;
  padding: 20px;
  border-radius: 6px;
}

.info-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.info-section h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: 600;
  color: #606266;
  min-width: 100px;
  margin-right: 10px;
}

.info-item span {
  color: #303133;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.image-item {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid #e4e7ed;
  transition: all 0.3s;
}

.image-item:hover {
  border-color: #409EFF;
  transform: scale(1.05);
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-overlay {
  opacity: 1;
}

.image-overlay i {
  color: #fff;
  font-size: 24px;
}

.no-images {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.no-images i {
  font-size: 48px;
  margin-bottom: 10px;
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

/* 图片预览对话框样式 */
.image-preview-dialog {
  width: auto !important;
  max-width: 80%;
}
</style>